﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using YawetagLib.Reflection;

namespace YawetagLib.Data.Xml
{
    internal sealed class XProxyBuilder : DynamicTypeBuilder
    {
        private const string REFERENCE_GETTER_CALLBACK_FIELD_NAME = "referenceGetterCallback";
        private const string REFERENCE_GETTER_CALLBACK_NAME = "ReferenceGetterCallback";
        private static readonly Type REFERENCE_GETTER_CALLBACK_TYPE = typeof(Func<object, string, object>);

        private XProxyBuilder(Type baseType)
            : base(baseType, null)
        {
        }

        public static TEntity CreateInstance<TEntity>(Func<object, string, object> referenceGetterCallback)
        {
            Type proxyType = new XProxyBuilder(typeof(TEntity)).GetBuiltType();
            TEntity instance = (TEntity)Activator.CreateInstance(proxyType);
            instance.GetType().GetProperty(REFERENCE_GETTER_CALLBACK_NAME).SetValue(instance, referenceGetterCallback, null);

            return instance;
        }

        protected override void DefineFields() 
        {
            FieldBuilder field = TypeBuilder.DefineField(REFERENCE_GETTER_CALLBACK_FIELD_NAME, REFERENCE_GETTER_CALLBACK_TYPE, 
                FieldAttributes.Private | FieldAttributes.InitOnly);

            Fields.Add(REFERENCE_GETTER_CALLBACK_FIELD_NAME, field);
        }

        protected override void DefineProperties()
        {
            DefineProperty(Fields[REFERENCE_GETTER_CALLBACK_FIELD_NAME], REFERENCE_GETTER_CALLBACK_NAME, REFERENCE_GETTER_CALLBACK_TYPE);

            foreach (PropertyInfo pInfo in GetReferencesPropertyInfo()) 
            {
                string propertyName = pInfo.Name;
                Type propertyType = pInfo.PropertyType;

                PropertyBuilder propertyBuilder = TypeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);

                DefineReferencePropertyGetter(propertyBuilder, propertyName, propertyType);
            }
        }

        private IEnumerable<PropertyInfo> GetReferencesPropertyInfo()
        {
            return BaseType.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(i => i.IsXReferenceProperty());
        }

        private void DefineReferencePropertyGetter(PropertyBuilder propertyBuilder, string propertyName, Type propertyType)
        {
            MethodBuilder methodBuilder = TypeBuilder.DefineMethod("get_" + propertyName,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual,
                propertyType, Type.EmptyTypes);

            ILGenerator il = methodBuilder.GetILGenerator();
            Label beginningOfMethod = il.DefineLabel();
            Label endOfMethod = il.DefineLabel();

            il.MarkLabel(beginningOfMethod);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, BaseType.GetMethod("get_" + propertyName));
            il.Emit(OpCodes.Dup);
            il.Emit(OpCodes.Ldnull);
            il.Emit(OpCodes.Ceq);
            il.Emit(OpCodes.Brfalse_S, endOfMethod);

            il.Emit(OpCodes.Pop);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, Fields[REFERENCE_GETTER_CALLBACK_FIELD_NAME]);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldstr, propertyName);
            il.Emit(OpCodes.Callvirt, REFERENCE_GETTER_CALLBACK_TYPE.GetMethod("Invoke", new[] { typeof(object), typeof(string) }));
            il.Emit(OpCodes.Castclass, propertyType);
            il.Emit(OpCodes.Call, BaseType.GetMethod("set_" + propertyName));
            il.Emit(OpCodes.Br_S, beginningOfMethod);

            il.MarkLabel(endOfMethod);
            il.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(methodBuilder);
        }

        protected override string BuilderSignature
        {
            get { return "XProxy"; }
        }
    }
}
